package org.knife.springbootlearn.core.spring.domain.service.impl;

import org.knife.springbootlearn.core.spring.domain.service.AppContextInitListener;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.Map;

/**
 * 自动监听实现了{@link AppContextInitListener}的bean，并执行其初始化方法
 * @author tianhao.luo@hand-china.com
 * @version 1.0
 * @date 2021年11月23日 星期二 2:04 下午
 * @description
 * @since 1.0
 */
public class ApplicationListenerBean implements ApplicationListener {

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ContextRefreshedEvent) {
            ApplicationContext applicationContext = ((ContextRefreshedEvent) event).getApplicationContext();
            Map<String, AppContextInitListener> beanMap = applicationContext.getBeansOfType(AppContextInitListener.class);
            beanMap.forEach((k, v) -> {
                v.contextInitialized(applicationContext);
            });
        }
    }
}
